<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Modules</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Python, modules, tutorial, programming language, learn Python">
<meta name="description" content="In this chapter of the Python tutorial, we will
work with modules.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">

<a href="/" title="Home">Home</a>&nbsp;
<a href="..">Contents</a>


<h1>Modules</h1>

<p>
In this part of the Python programming tutorial, we will talk about 
Python modules. 
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 

<p>
A <b>module</b> is a file in which we have Python code. 
The modules in Python have the <b>.py</b> extension. 
</p>

<p>
There are several ways to manage Python code:
</p>

<ul>
    <li>functions</li>
    <li>classes</li>
    <li>modules</li>
    <li>packages</li>
</ul>

<p>
Python modules are used to organize Python code. For example, database related 
code is placed inside a database module, security code in a security module etc. 
Smaller Python scripts can have one module. But larger programs are split into
several modules. Modules are grouped together to form packages.
</p>


<h2>Module names</h2>

<p>
A module name is the file name with the .py extension. When we have a file
called empty.py, empty is the module name. The <code>__name__</code> is a variable
that holds the name of the module being referenced. The current module, the module
being executed (called also the main module) has a special name: <code>'__main__'</code>.
With this name it can be referenced from the Python code.
</p>

<p>
We have two files. empty.py and modulename.py. The second module is the main module, which
is executed. It imports the first module. Modules are imported using the <code>import</code>
keyword.
</p>

<pre class="code">
$ cat empty.py
"""
An empty module
"""
</pre>

<p>
This is empty.py module. 
</p>

<pre class="code">
#!/usr/bin/python

import empty
import sys

print __name__
print empty.__name__
print sys.__name__
</pre>

<p>
In this code example we import two modules. One built-in module (sys) and one custom
module (empty). We print the names of modules to the console.  
</p>

<pre>
$ ./modulename.py 
__main__
empty
sys
</pre>

<p>
The name of the module, which is being executed is always <code>'__main__'</code>. 
Other modules are named after the file name. 
Modules can be imported into other modules using the <code>import</code> keyword. 
</p>


<h2>Locating modules</h2>

<p>
When a module is imported the interpreter first searches for a built-in module 
with that name. If not found, it then searches in a list of directories given by the 
variable <code>sys.path</code>. The <code>sys.path</code> is a list of strings that 
specifies the search path for modules. It consists of the current working directory, 
directory names specified in the PYTHONPATH environment variable plus some additional
installation dependent directories. If the module is not found, an ImportError is raised. 
</p>

<pre class="code">
#!/usr/bin/python

import sys
import textwrap

sp = sorted(sys.path)
dnames = ', '.join(sp)

print textwrap.fill(dnames)
</pre>

<p>
The script prints all directories from <code>sys.path</code> variable.
</p>

<pre class="explanation">
import textwrap
</pre>

<p>
The textwrap module is used for easy formatting of paragraphs.
</p>

<pre class="explanation">
sp = sorted(sys.path)
</pre>

<p>
We retrieve a list of directories from the sys.path variable and sort them.
</p>

<pre class="explanation">
dnames = ', '.join(sp)
</pre>

<p>
We make a string out of the list.
</p>

<pre>
$ ./syspath.py 
/home/janbodnar/programming/python/modules,
/usr/lib/pymodules/python2.7, /usr/lib/python2.7, /usr/lib/python2.7
/dist-packages, /usr/lib/python2.7/dist-packages/PIL,
...
</pre>

<p>
Sample output.
</p>


<h2>The import keyword</h2>

<p>
The <code>import</code> keyword can be used in several ways. 
</p>

<pre>
from module import *
</pre>

<p>
This construct will import all Python definitions into the namespace of another 
module. There is one exception. Objects beginning with underscore character _ are 
not imported. They are expected to be used only internally by the module being 
imported. This way of importing modules is not recommended. 
</p>

<pre class="code">
#!/usr/bin/python

from math import *

print cos(3)
print pi
</pre>

<p>
This import construct has imported all definitions from the built-in <code>math</code> module. 
We can call the math funtcions directly, without referencing the math module. 
</p>

<pre>
$ ./everything.py 
-0.9899924966
3.14159265359
</pre>

<p>
The use of this import construct may result in namespace pollution. We may have several 
objects of the same name and their definitions can be overriden. 
</p>

<pre class="code">
#!/usr/bin/python

from math import  *

pi = 3.14

print cos(3)
print pi
</pre>

<p>
The example will print 3.14 to the console. Which may not be, what we wanted. The namespace 
pollution may become critical in larger projects. 
</p>

<p>
The following example will show definitions, that are not being 
imported using this import construct. 
</p>

<pre class="code">
#!/usr/bin/python

"""
names is a test module
"""

_version = 1.0

names = ["Paul", "Frank", "Jessica", "Thomas", "Katherine"]

def show_names():
   for i in names:
      print i

def _show_version():
   print _version
</pre>

<p>
This is the names.py module. 
</p>

<pre class="code">
#!/usr/bin/python

from names import *

print locals()

show_names()
</pre>


<p>
The _version variable and the _show_version() function are not imported into 
the private.py module. We don't see them in the namespace. The 
<code>locals()</code> function give us all the definitions available in the 
private module. 
</p>

<pre>
$ ./private.py 
{'__builtins__': &lt;module '__builtin__' (built-in)&gt;, '__file__': './private.py', 
'show_names': &lt;function show_names at 0xb7dd233c&gt;, 
'names': ['Paul', 'Frank', 'Jessica', 'Thomas', 'Katherine'],
 '__name__': '__main__', '__doc__': None}
Paul
Frank
Jessica
Thomas
Katherine
</pre>

<hr class="btm">

<pre>
from module import fun, var
</pre>

<p>
This import construct imports only specific objects from a module. This way we 
import only definitions that we need. 
</p>


<pre class="code">
#!/usr/bin/python

from math import sin, pi

print sin(3)
print pi
</pre>

<p>
We import two objects from the <code>math</code> module. There is no way, 
how we could reference other definitions like e.g. a cos function. 
</p>

<pre class="code">
#!/usr/bin/python

from names import _version, _show_version

print _version
_show_version()
</pre>

<p>
We could also import definitions beginning with an underscore. But this is a bad practice. 
</p>

<pre>
$ ./imnames.py 
1.0
1.0
</pre>

<hr class="btm">

<pre>
import module
</pre>

<p>
The last construct is most widely used. It prevents the namespace pollution 
and enables to access all definitios
from a module. 
</p>

<pre class="code">
#!/usr/bin/python

import math

pi = 3.14

print math.cos(3)
print math.pi
print math.sin(3)
print pi
</pre>

<p>
In this case, we reference the definitions via the module name. 
As we can see, we are able to use both pi variables. Our definition and 
the one from the <code>math</code> module.
</p>

<pre>
$ ./widely.py 
-0.9899924966
3.14159265359
0.14112000806
3.14
</pre>

<pre class="code">
#!/usr/bin/python

# importas.py

import math as m

print m.pi
print m.cos(3)
</pre>

<p>
We can change the name through which we can reference the module. To do 
this, we use the <code>as</code> keyword. 
</p>

<pre>
$ ./importas.py 
3.14159265359
-0.9899924966
</pre>

<hr class="btm">

<p>
An <code>ImportError</code> is raised, if a module cannot be imported.
</p>

<pre class="code">
#!/usr/bin/python

try:
    import empty2
except ImportError, e:
    print 'Failed to import:', e
</pre>

<p>
We have not created an empty2 module. Therefore an exception is raised.
</p>

<pre>
$ ./importerror.py
Failed to import: No module named empty2
</pre>

<p>
Output.
</p>


<!--<h2>Reloading modules</h2>

<p>
Python loads a module once and keeps it in memory, 
until you reload it. Calling reload is one way to ensure that your 
module is up-to-date even if the file on disk has changed. 
</p>

<pre class="code">

</pre>

<p>

</p>-->


<h2>Executing modules</h2>

<p>
Modules can be imported into other modules or they can be also executed. 
Module authors often create a testing suite
to test the module. Only if the module is executed as a script, 
the <code>__name__</code> attribute equals to <code>__main__</code>. 
</p>

<p>
We will demonstrate this on a fibonacci module. Fibonacci numbers is 
a sequence of numbers, where each is the sum
of its two immediate predecessors. 
</p>


<pre class="code">
#!/usr/bin/python

"""
A module containing the fibonacci
function. 
"""

def fib(n):
    a, b = 0, 1
    while b &lt; n:
        print b,
        (a, b) = (b, a + b)


# testing

if __name__ == '__main__':
   fib(500)
</pre>

<p>
The module can be normally imported as usual. The module can be also executed. 
</p>

<pre>
$ ./fibonacci.py 
1 1 2 3 5 8 13 21 34 55 89 144 233 377
</pre>

<p>
If we do import the fibonacci module, the test is not executed automatically. 
</p>

<pre>
>>> import fibonacci as fib
>>> fib.fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377
</pre>

<p>
The fibonacci module is imported and the fib() function is executed. 
</p>


<h2>The dir() function</h2>

<p>
The built-in <code>dir()</code> function gives a sorted list of strings 
containing the names defined by a module.
</p>

<pre class="code">
#!/usr/bin/python

"""
This is dirfun module 
"""

import math, sys

version = 1.0

names = ["Paul", "Frank", "Jessica", "Thomas", "Katherine"]

def show_names():
  
   for i in names:
      print i

print dir(sys.modules['__main__']) 
</pre>

<p>
In this module, we import two system modules. We define a variable, a list and
a function. 
</p>

<pre class="explanation">
print dir(sys.modules['__main__']) 
</pre>

<p>
The <code>dir()</code> function returns all the names available in the
current namespace of the module. <code>'__main__'</code> is the name of the current
module. The <code>sys.modules</code> is a dictionary that maps module names 
to modules which have already been loaded.
</p>

<pre>
$ ./dirfun.py
['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'math', 
'names', 'show_names', 'sys', 'version']
</pre>

<p>
We can see some built-in names like '__file__' or '__name__' and all the others, that
we have defined. 
</p>


<h2>The globals() function</h2>

<p>
The <code>globals()</code> function returns a dictionary that represents 
the current global namespace. It is a dictionary of global names and their
values. It is the dictionary of the current module.
</p>

<pre class="code">
#!/usr/bin/python

import sys
import textwrap

version = 1.0

def myfun():
    pass

gl = globals()    
gnames = ', '.join(gl)

print textwrap.fill(gnames) 
</pre>

<p>
We use the globals() function to print all the global names of the current
module.
</p>

<pre>
$ ./globalsfun.py
__builtins__, __file__, textwrap, __package__, sys, myfun, version,
__name__, gl, __doc__
</pre>

<p>
These are the global names of the current module.
</p>


<h2>The __module__ attribute</h2>

<p>
The <code>__module__</code> class attribute has the name of the module in which 
the class is defined. 
</p>

<pre class="code">
"""
module animals
"""

class Cat:
  pass

  
class Dog:
  pass
</pre>

<p>
This are the contents of the animals.py file. We have two classes. 
</p>

<pre class="code">
#!/usr/bin/python

from animals import Cat

class Being:
    pass
  
  
b = Being()
print b.__module__

c = Cat()
print c.__module__
</pre>

<p>
In this code we use the <code>__module__</code> attribute.
</p>

<pre class="explanation">
from animals import Cat
</pre>

<p>
From the animals module, we import the Cat class. 
</p>

<pre class="explanation">
class Being:
    pass
</pre>

<p>
In the current module, we define a class Being.
</p>

<pre class="explanation">
b = Being()
print b.__module__
</pre>

<p>
An instance of the Being class is created. We print the name
of its module. 
</p>

<pre class="explanation">
c = Cat()
print c.__module__
</pre>

<p>
We create an object from the Cat class. We also print the module,
where it was defined. 
</p>

<pre>
$ ./mclass.py
__main__
animals
</pre>

<p>
The current module's name is __main__. And the Cat's module name is
animals.
</p>

<p>
This chapter was about modules in Python.
</p>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>


<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified December 23, 2012  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

